package com.jack.thinking.java._22.swing.button;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.utils.SwingConsole;

/**
 * 多选列表。
 * @author wangbingwu
 *
 */
public class List extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String[] flavors = {
		"Jack", "Jane", "Li", "Zhou", "Wang", "Ly"
	};
	
	private DefaultListModel<String> lItems = new DefaultListModel<>();
	private JList<String> lst = new JList<>(lItems);
	private JTextArea t = new JTextArea(flavors.length, 20);
	private JButton b = new JButton("Add Item");
	private ActionListener bl = new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			if(count < flavors.length) {
				lItems.add(0, flavors[count++]);
			}else {
				b.setEnabled(false);
			}
		}
	};
	
	private ListSelectionListener ll = new ListSelectionListener() {
		
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if(e.getValueIsAdjusting()) {  // 当组件拥有 shift 或是 ctrl 等拖拽方式， 这个在拖拽期间返回true， 拖拽完成后返回false。
				return;
			}
			t.setText("");
			for(String item : lst.getSelectedValuesList()) {
				t.append(item + "\n");
			}
		}
	};
	private int count = 0;
	
	public List() {
		t.setEditable(false);
		setLayout(new FlowLayout());
		Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.BLACK);
		lst.setBorder(brd);
		t.setBorder(brd);
		for(int i = 0; i < 2; i++) {
			lItems.addElement(flavors[count++]);
		}
		add(t);
		add(lst);
		add(b);
		
		lst.addListSelectionListener(ll);
		b.addActionListener(bl);
	}
	
	public static void main(String[] args) {
		SwingConsole.run(new List(), 250, 375);
	}
}
